﻿using System;
using System.Linq;
using System.Collections.Generic;

namespace cludg.Domain.Content.Stories
{
	public class Story : IContent, ITaggable
	{
		public virtual string Id { get; set; }
		public virtual Users.User Author { get; set; }
		public virtual Users.User OfferAuthor { get; set; }
		public virtual string AnonymouseAuthorName { get; set; }
		public virtual DateTime CreationTime { get; set; }
		public virtual StorySubject Subject { get; set; }
		public virtual string Title { get; set; }
		public virtual string Body { get; set; }
		public virtual int Rate { get; set; }
		public virtual string UniqueName { get; set; }
		public virtual int ViewCount { get; set; }

		#region Comments
		private readonly IList<Comment> _comments = new List<Comment>();
		public virtual IEnumerable<Comment> Comments
		{
			get { return _comments; }
		}

		public virtual void AddComment(Comment comment)
		{
			_comments.Add(comment);
			comment.Story = this;
		}

		public virtual void UpdateComment(Comment comment)
		{
			var existCommetn = _comments.Where(x => x.Id == comment.Id).FirstOrDefault();
			_comments.Remove(existCommetn);
			_comments.Add(comment);
			comment.Story = this;
		}

		public virtual IEnumerable<Comment> FirstLevelComments
		{
			get { return Comments.Where(x => x.ParentComment == null); }
		} 
		#endregion

		public override string ToString()
		{
			return string.Format("Story: Id='{0}', Title='{1}'", Id, Title);
		}

		#region Tags
		private readonly IList<Tag> _tags = new List<Tag>();
		public virtual IEnumerable<Tag> Tags
		{
			get { return _tags; }
			set
			{
				if (value == null)
				{
					_tags.Clear();
					return;
				}

				// Remove deleted tags
				var existTags = _tags.Intersect(value).ToList();
				_tags.Clear();
				foreach (var existTag in existTags)
				{
					_tags.Add(existTag);
				}

				// Add new tags
				foreach (var tag in value.Where(tag => !_tags.Contains(tag)))
				{
					tag.ContentId = Id;
					_tags.Add(tag);
				}
			}
		}

		public virtual string GetTagsAsString(char separator)
		{
			string result = "";
			foreach (var tag in Tags)
			{
				if (result != "")
					result = result + separator + " ";
				result = result + tag.Name;
			}
			return result;
		}

		public virtual void SetTagsAsString(string value, char separator)
		{
			if (!string.IsNullOrWhiteSpace(value))
			{
				Tags = from tag in value.Split(separator)
					   select new Tag { Name = tag.Trim() };
			}
			else
			{
				Tags = null;
			}

		} 
		#endregion
	}
}
